﻿Public Class ChatManager

    Public Shared Property Chats() As List(Of ChatMessage)

        Get

            Dim ocCache As System.Runtime.Caching.ObjectCache = System.Runtime.Caching.MemoryCache.Default
            Dim cmChats As List(Of ChatMessage) = Nothing

            If ocCache.Contains("Chats") Then

                cmChats = DirectCast(ocCache.Get("Chats"), List(Of ChatMessage))

            Else

                cmChats = New List(Of ChatMessage)
                ocCache.Add("Chats", cmChats, New System.Runtime.Caching.CacheItemPolicy())

            End If

            Return cmChats

        End Get

        Set(value As List(Of ChatMessage))

            Dim ocCache As System.Runtime.Caching.ObjectCache = System.Runtime.Caching.MemoryCache.Default

            If ocCache.Contains("Chats") Then

                ocCache("Chats") = value

            Else

                ocCache.Add("Chats", value, New System.Runtime.Caching.CacheItemPolicy())

            End If

        End Set

    End Property


    Public Class ChatMessage

        Public Property User As Trebuchet.User
        Public Property Message As String = ""
        Public Property MessageDate As DateTime = DateTime.Today

        Public Sub New(ByVal tuUser As Trebuchet.User, ByVal strMessage As String, ByVal dtDate As DateTime)

            User = tuUser
            Message = strMessage
            MessageDate = dtDate

        End Sub

    End Class

    Public Shared Function SendMessage(Message As ChatMessage) As Boolean
        Try

            If Chats Is Nothing Then
                Chats = New List(Of ChatMessage)
            End If
            'Add message to Database
            Chats.Add(Message)

            Return True
        Catch
            Return False
        End Try
    End Function

    Public Shared Function RecieveMessage() As List(Of ChatMessage)

        CleanupOldChats()

        'Get list of messages
        Return Chats

    End Function

    Public Shared Sub CleanupOldChats()
        Dim cmChats As List(Of ChatMessage) = Nothing

        cmChats = Chats

        cmChats.RemoveAll(Function(Chat As ChatMessage) Chat.MessageDate <= Now().Subtract(New TimeSpan(8, 0, 0)))

    End Sub

End Class
